<template>
  <div :class="$options.name">
    <el-upload
      :on-remove="handleRemove"
      v-show="!resultImg"
      class="upload-el"
      accept="image/*"
      ref="fileUpload"
      name="pic"
      :action="action"
      :data="uploadData"
      :on-change="selectChange"
      :show-file-list="false"
      :auto-upload="false"
      :http-request="httpRequest">
      <img :src="image" v-if="judgeId!==0" class="edit-image" >
      <div v-if="isShowLetter&&judgeId!==0" class="update-img-desc">* 点击图片进行重新选择！</div>
      <div  v-if="judgeId===0">
        <span class="icon upload-icon"/>
        <el-button class="choose-button">选择图片</el-button>
      </div>
    </el-upload>
    <figure
      v-show="resultImg"
      class="result-img">
      <div>
        <img :src="resultImg" @click="updateCropper">
<!--        <span v-if="resultImg" class="update-img-desc">*点击图片重新上传</span>-->
      </div>
    </figure>
    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg"
      :width="width"
      :height="height"
    />
  </div>
</template>

<script>
import Cropper from './Cropper.vue'

export default {
  name: 'UploadImg',
  components: {
    Cropper
  },
  props: {
    //判断父组件点击的是添加还是编辑
    judgeId: Number,
    //向父组件获取点击编辑按钮时的图片URL
    image: String,
    width:Number,
    height:Number,
    //判断是否需要展示”点击图片进行重新选择“文字
    isShowLetter:Boolean
  },
  data () {
    return {
      uploadData: { // 上传需要的额外参数
        siteId: 1,
        source: 1,
        fileName: ''
      },
      action: 'http://106.13.150.219:8090/api/Common/CommonMethod/PostUploadImage', // 上传地址，必填
      cropperImg: '', // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      uploadFile: '', // 裁剪后的文件
      resultImg: '' // 上传成功，后台返回的路径
    }
  },
  created () {
    this.$bus.$on('widthAndHeight',(value)=>{
      console.log(value)
    })
  },
  methods: {
    // submit 之后会触发此方法
    httpRequest (request) {
      // console.log('+++++++++++++')
      // console.log(JSON.stringify(request))
      //action:裁剪后的图片地址
      //data:裁剪后的图片名称/图片数量/图片id
      //filename:图片名称
      const {
        action,
        data,
        filename
      } = request
      // 新建formDate对象
      let formData = new FormData()
      for (let key in data) {
        formData.append(key, data[key])
      }

      // 文件单独push,第三个参数指定上传的文件名
      formData.append(filename, this.uploadFile, data.fileName)
      //请求接口
      this.axios({
        headers: {
          contentType: 'multipart/form-data' // 需要指定上传的方式
        },
        url: action,
        method: 'post',
        data: formData,
        timeout: 200000000 // 防止文件过大超时
      }).then((resp) => {
        this.$message.success('图片上传成功')
        this.resultImg = resp.Url + resp.Image // 上传成功后展示的图片
        this.$emit('showImage', this.resultImg)
      }).catch(err => {
        console.log(err)
      })
    },
    // 选择文件
    selectChange (file) {
      const {
        raw,
        name
      } = file
      this.openCropper(raw)
      this.uploadData.fileName = name
    },
    /**
     * @param {file} 上传的文件
     */
    openCropper (file) {
      let files = file
      let isLt5M = files.size > (5 << 20)
      if (isLt5M) {
        this.$message.error('请上传5M内的图片')
        return false
      }
      console.log('1111',files)
      let reader = new FileReader()
      reader.onload = e => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        console.log('2222',data)
        this.cropperImg = data
      }
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files)
      console.log('3333',reader)
      this.showCropper = true
    },
    // 上传图片
    uploadImg (file) {
      this.uploadFile = file
      this.$refs.fileUpload.submit()
      this.showCropper = false
      //提交后清空文件
      this.$refs.fileUpload.clearFiles()
    },
    // 更新图片
    updateCropper () {
      this.$refs.fileUpload.$children[0].$el.click()
    },
    // 关闭窗口
    closeDialog () {
      this.showCropper = false
    },
    handleRemove (file, fileList) {
      console.log(file)
      console.log(fileList)
    },

  }
}
</script>

<style lang="scss" scoped>
.UploadImg {
  .el-upload {
    display: block;
    width: 100px;
    margin: 30px auto 0;
  }

  .upload-icon {
    display: block;
    height: 44px;
    width: 52px;
    background-image: url(~@/assets/img/upload-image.png);
    background-position: 100% 100%;
    margin: 0 auto 20px;
  }

  .video-image {
    display: flex;
  }

  .result-img img {
    height: 100px;
    width: 100px;
  }
}

.edit-image {
  height: 100px;
  width: 100px;
}

.choose-button {
  margin-top: 10px;
}

 .update-img-desc {
  color: #DC143C !important;
  font-size: 12px !important;
  font-weight: bold !important;
}

 /deep/ .el-tag{
   border: 0;
 }

</style>
